Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Is there a way to efficiently "pivot" a multidimensional array?

I have an array of arrays formatted the following way:

[['BTC', '2022-04-27', '39151.53'],
 ['BTC', '2022-04-26', '37730.20'],
 ['BTC', '2022-04-25', '39151.53'],
 ['ETH', '2022-04-27', '39151.53'],
 ['ETH', '2022-04-26', '37730.20'],
 ['ETH', '2022-04-25', '39151.53']]

What I would like to end up with is:

[['Date', 'BTC, 'ETH'],
 ['2022-04-27', '39151.53', '39151.53'],
 ['2022-04-26', '37730.20', '39151.53'],
 ['2022-04-25', '39151.53', '39151.53']]

Is there any non-complicated way to solve it?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could take an object with the types fo the columns and the indices of the target. Then find the row and assign the type to the wanted cell.

const
    data = [['BTC', '2022-04-27', '39151.53'], ['BTC', '2022-04-26', '37730.20'], ['BTC', '2022-04-25', '39151.53'], ['ETH', '2022-04-27', '39151.53'], ['ETH', '2022-04-26', '37730.20'], ['ETH', '2022-04-25', '39151.53']],
    types = { Date: 0, BTC: 1, ETH: 2 },
    result = data.reduce((r, [type, date, value]) => {
        let row = r.find(a => a[types.Date] === date);
        if (!row) r.push(row = [date, ...Array(Object.keys(types).length - 1).fill('0')]);
        row[types[type]] = value;
        return r;
    }, [Object.keys(types)]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

It looks like the OP needs the inner arrays indexed by the date field. This can be done with reduce. Once there's an index, walk through the keys (dates) and collect the values associated with each date.

const array = [['BTC', '2022-04-27', '39151.53'],
 ['BTC', '2022-04-26', '37730.20'],
 ['BTC', '2022-04-25', '39151.53'],
 ['ETH', '2022-04-27', '39151.53'],
 ['ETH', '2022-04-26', '37730.20'],
 ['ETH', '2022-04-25', '39151.53']];

const dateIndex = array.reduce((acc, a) => {
  let date = a[1];
  if (!acc[date]) acc[date] = [];
  acc[date].push(a);
  return acc;
}, {});


let result = [['Date', 'BTC', 'ETH']];
Object.keys(dateIndex).map(date => {
  let values = dateIndex[date].map(arr => arr[2]);
  result.push([date, ...values]);
});

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here another solution using reduce().

This first creates a JavaScript object which would allow for quick lookups of a specific value for a given currency and date within a program and then transforms that object to create the result requested by OP. It will also throw an error for incorrect input data when e.g. there would be two values for a given currency and date.

const input = [
  ["BTC", "2022-04-27", "39151.53"],
  ["BTC", "2022-04-26", "37730.20"],
  ["BTC", "2022-04-25", "39151.53"],
  ["ETH", "2022-04-27", "39151.53"],
  ["ETH", "2022-04-26", "37730.20"],
  ["ETH", "2022-04-25", "39151.53"],
];

function pivot(input){
  return input.reduce((perDay, [currency, date, value]) => {
    if(perDay[date]) {
      // we already have a value for this day
      if(perDay[date][currency]){
        // we already have a value for this currency and day => error
        throw new Error(`Two values for for the same day. Currency: ${currency}, Day: ${date}`);
      }
      // add value for another currency for that day
      else perDay[date][currency] = value;
    } else perDay[date] = { [currency]: value };
    return perDay; 
  }, {})
}

// result as a JS object which will allow quick lookups
const pivotted = pivot(input);
console.log("Result as JavaScript object")
console.log(pivotted);

// result transformed to your expected result
const result = Object.entries(pivotted).map(([date, values]) => [date, ...Object.values(values)]);
result.unshift(['Date', 'BTC', 'ETH']);
console.log("Result as JavaScript nested array")
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda